package eg.edu.eelu.fyp2013.jdetector.gui;

import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;

/**
 * @author Amr
 *
 */
public class HistogramGraphPanel extends JPanel {

	private static final long serialVersionUID = 1L;
	
	private int[]histogram= new int[256];
	private int[]visibileHistogram= new int[256];
	
	private float xScale=1;
	private float yScale=1;

	private float zoomFactor=1;
	/**
	 * @return the histogram
	 */
	public int[] getHistogram() {
		return histogram;
	}

	/**
	 * @param histogram the histogram to set
	 */
	public void setHistogram(int[] histogram) {
		this.histogram = histogram;
		reinitVisibleHistogram();
		repaint();
	}

	public void reinitVisibleHistogram() {
		visibileHistogram= new int[Math.round(256*xScale)];
		for (int i = 0; i < histogram.length; i++) {
			int targetIndex = Math.round(i * xScale);
			visibileHistogram[targetIndex]+=histogram[i];
		}
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(256,256);
//		for (int i = 0; i < histogram.length; i+=3) {
//			histogram[i]=i;
//		}
		this.setLayout(new GridBagLayout());
		this.setBackground(Color.white);
		this.addComponentListener(new java.awt.event.ComponentAdapter() {
			public void componentResized(java.awt.event.ComponentEvent e) {
				xScale= getWidth()/256.0f;
				yScale= getHeight()/256.0f;
				reinitVisibleHistogram();
				repaint();
			}
		});
		repaint();
	}
	
	


	/**
	 * This is the default constructor
	 */
	public HistogramGraphPanel() {
		super();
		initialize();
	}
	
	
	
	/* (non-Javadoc)
	 * @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
	 */
	@Override
	protected void paintComponent(Graphics g) {
//		System.out.println("paint component called");
		super.paintComponent(g);
		g.setColor(Color.RED);
		g.drawLine(realX(0), realY(0), realX(0), realY(255));
		g.drawLine(realX(0), realY(0), realX(255), realY(0));
		
		
		g.setColor(Color.BLACK);
		for (int i = 0; i < histogram.length; i++) {
			g.drawLine(realX(i), realY(0), realX(i), realY(visibileHistogram[Math.round(i*xScale)]*zoomFactor));
		}		
	}
	
	private int realX(int x){
		return  Math.round(x* xScale);
	}
	private int realY(float y){
		return getHeight()-(Math.round(y* yScale)-1);
	}

	public void setZoomFactor(float zoomFactor) {
		this.zoomFactor = zoomFactor;
		repaint();
	}

	



}  //  @jve:decl-index=0:visual-constraint="10,10"